<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="search()">
      <el-form-item>
        <el-input v-model="dataForm.userId" placeholder="uid"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.nickname" placeholder="昵称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.phone" placeholder="手机号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="search()">查询</el-button>

      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      style="width: 100%;"
    >
      <el-table-column prop="userId" header-align="center" align="center" label="uid"></el-table-column>
      <el-table-column prop="nickname" header-align="center" align="center" label="昵称"></el-table-column>
      <el-table-column prop="avatar" header-align="center" align="center" label="头像">
        <template slot-scope="scope">
          <img :src="scope.row.avatar" style="width:40px;height:40px;">
        </template>
      </el-table-column>
      <el-table-column prop="phone" header-align="center" align="center" label="手机号"></el-table-column>
      <el-table-column prop="wxNumber" header-align="center" align="center" label="微信号"></el-table-column>
      <el-table-column header-align="center" align="center" label="二维码">
        <template slot-scope="scope">
          <img v-if="scope.row.wxQrcode" :src="scope.row.codeImg" style="width:40px;height:40px;">
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column prop="gmtCreate" header-align="center" align="center" label="注册时间"></el-table-column>
      <el-table-column prop="lastLoginAt" header-align="center" align="center" label="最后登录时间"></el-table-column>
      <el-table-column prop="isForbidden" header-align="center" align="center" label="登录状态
      ">
        <template slot-scope="scope">
          <!-- <div>{{scope.row.isAlive==1?'启用':''}}</div>
          <div class="active">{{ scope.row.isAlive === 0 ? '禁用': '' }}</div>-->
          <el-switch
            v-model="scope.row.isForbidden"
            :active-value="1"
            :inactive-value="0"
            @change="changeSwitch(scope.row.id)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" label="操作">
        <template slot-scope="scope">
          <el-button v-if="scope.row.phone" type="text" size="small"
                     @click="bindphone(scope.row.id)">解绑手机号
          </el-button>
          <el-button v-else type="text" size="small"
                     @click="unbindphonw(scope.row.id)">绑定手机号
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <el-dialog title="绑定手机号" :close-on-click-modal="false" :visible.sync="bindphoneshow"
    >
      <el-form ref="dataPhone" :model="dataPhone" :rules="dataRule">
        <el-form-item label="请输入要绑定的手机号：" prop='phone'>
          <el-input v-model="dataPhone.phone" style="width: 300px;" clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="bindphoneshow = false">取消</el-button>
        <el-button type="primary" @click="submitphone()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import QRCode from "qrcode";

  export default {
    data() {
      return {
        dataPhone: {},
        bindphoneshow: false,
        dataForm: {
          key: "",
          id: '',
          userId: '',
          nickname: '',
          phone: '',

        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        addOrUpdateVisible: false,
        dataRule: {
          phone: [
            { required: true, message: "实名认证手机号不能为空", trigger: "blur" },
            {pattern: /^1[3456789]\d{9}$/,message: '请输入正确的手机号', trigger: 'blur'}
          ],
        },
      };
    },
    activated() {
      this.getDataList();
    },
    methods: {
      search() {
        this.pageIndex = 1
        this.getDataList()
      },
      // 获取数据列表
      getDataList() {
        this.dataListLoading = true;
        let obj = {
          page: this.pageIndex,
          limit: this.pageSize,
          key: this.dataForm.key
        };
        if (this.dataForm.phone) {
          obj.number = this.dataForm.phone;
        }
        if (this.dataForm.nickname) {
          obj.nickname = this.dataForm.nickname;
        }
        if (this.dataForm.userId) {
          obj.userId = this.dataForm.userId + "";
        }
        this.$http({
          url: this.$http.adornUrl("/user/appuser/userList"),
          method: "get",
          params: this.$http.adornParams(obj)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list;
            this.totalPage = data.page.totalCount;
            let len = data.page.list.length;
            for (let i = 0; i < len; i++) {
              let codeUrl = this.dataList[i].wxQrcode || "";
              let opts = {
                errorCorrectionLevel: "H",
                type: "image/jpeg",
                rendererOpts: {
                  quality: 0.3
                }
              };
              QRCode.toDataURL(codeUrl, opts, (err, url) => {
                this.dataList[i].codeImg = url;
              });
            }
          } else {
            this.dataList = [];
            this.totalPage = 0;
          }
          this.dataListLoading = false;
        });
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val;
        this.pageIndex = 1;
        this.getDataList();
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val;
        this.getDataList();
      },
      bindphone(id) {
        const obj = {
          id,
          phone: null
        }
        this.$confirm('确认解绑该手机号？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/user/appuser/updatePhone'),
            method: 'post',
            data: this.$http.adornData(obj)
          }).then(({data}) => {
            if(data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                onClose: () => {
                  this.getDataList()
                }
              });
            }
          }).catch(() => {
            this.$message.error(data.msg);
          })
        }).catch(() => {

        })
      },
      unbindphonw(id) {
        this.bindphoneshow = true
        this.$nextTick(()=> {
          this.$refs["dataPhone"].resetFields();
          this.dataPhone = {
            id: id
          }
        })
      },
      submitphone() {
        this.$refs["dataPhone"].validate(valid => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl('/user/appuser/updatePhone'),
              method: 'post',
              data: this.$http.adornData(this.dataPhone)
            }).then(({data}) => {
              if (data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  onClose: () => {
                    this.getDataList()
                    this.bindphoneshow = false
                  }
                });
              } else {
                this.$message.error(data.msg);
              }
            }).catch(() => {
              this.$message.error(data.msg);
            })
          }
        })
      },
      changeSwitch(id) {
        this.dataForm.id = id;
        // console.log(this.dataForm.id);
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/user/appuser/isForbidden/${this.dataForm.id}`
            ),
            method: "get",
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data.code == 500) {
              this.$message.error(data.msg);
            }
            this.getDataList();
          }).catch(e => {
            this.$message.error(data.msg);
          })

        }
      }
    }
  };
</script>
